'use client';

import { type ChangeEvent, type FormEvent, useEffect, useState } from 'react';
import { useMutation, useQuery } from '@tanstack/react-query';
import { clientQueryAllSection, updatePostTemplate } from '@/services/api';
import diff from 'microdiff';
import type { IDifference, IPostTemplate, ISectionClient } from '@/interfaces';
import useToast from '@/hooks/useToast';
import { getDiffData } from '@/lib/tool';
import Alert from '@/app/[locale]/alert/alert';
import AlertLoad from '@/app/[locale]/alert/load';
import Box from '@/app/[locale]/admin/common/box';
import Spinner from '@/app/[locale]/component/spinner/spinner';
import Nodata from '@/app/[locale]/common/nodata/nodata';
import type { PrefixedTTranslatedFields } from '@/lib/dictionaries';

export default function UpdatePostTemplateInfo({
  source,
  translatedFields,
}: {
  source: IPostTemplate;
  translatedFields: PrefixedTTranslatedFields<'postTemplateAdminPage'>;
}) {
  const { show } = useToast();
  const [form, setForm] = useState<{
    name?: string;
    overview?: string;
    sort?: number;
    sectionId?: string;
  }>({
    name: source.name,
    overview: source.overview ?? '',
    sort: source.sort,
    sectionId: source.section.id + '',
  });
  const [differenceData, setDifferenceData] = useState<IDifference[]>([]);
  const [isDisabledSave, setIsDisabledSave] = useState(true);

  useEffect(() => {
    const diffData = diff(
      {
        name: source.name,
        overview: source.overview ?? '',
        sort: source.sort,
        sectionId: source.section.id + '',
      },
      form,
    );
    setDifferenceData(diffData);
    setIsDisabledSave(diffData.length === 0);
  }, [form, source]);

  const clientQueryAllSectionQuery = useQuery(
    ['/forum', '/sections', '/client'],
    async () => {
      return (await clientQueryAllSection()) as ISectionClient[];
    },
  );

  const updatePostTemplateMutation = useMutation(updatePostTemplate);

  async function onClickSave(e: FormEvent<HTMLFormElement>) {
    try {
      e.preventDefault();
      e.stopPropagation();

      const data = getDiffData(differenceData);

      const id = source.id;
      await updatePostTemplateMutation.mutateAsync({
        id,
        data,
      });

      show({
        type: 'SUCCESS',
        message: translatedFields.operate.saveCompleted,
      });
    } catch (e) {
      updatePostTemplateMutation.reset();
      show({
        type: 'DANGER',
        message: e,
      });
    } finally {
      setDifferenceData([]);
    }
  }

  function onChangeForm(e: ChangeEvent<HTMLInputElement | HTMLSelectElement>) {
    const name = e.target.name;
    const value = e.target.value;

    if (name === 'sort') {
      setForm({ ...form, sort: parseInt(value) });
    } else {
      setForm({ ...form, [name]: value });
    }
  }

  return (
    <Box>
      <form onSubmit={onClickSave} className="vstack gap-4">
        <div>
          <label className="form-label">
            {translatedFields.properties.name}
          </label>
          <input
            type="text"
            className="form-control"
            name="name"
            value={form.name}
            onChange={onChangeForm}
            aria-describedby="name"
            placeholder={translatedFields.tip.namePlaceholder}
          />
        </div>

        <div>
          <label className="form-label">
            {translatedFields.properties.overview}
          </label>
          <input
            type="text"
            className="form-control"
            name="overview"
            value={form.overview}
            onChange={onChangeForm}
            aria-describedby="overview"
            placeholder={translatedFields.tip.overviewPlaceholder}
          />
        </div>

        <div>
          <label className="form-label">
            {translatedFields.properties.sort}
          </label>
          <input
            min={0}
            type="number"
            className="form-control"
            name="sort"
            value={form.sort}
            onChange={onChangeForm}
            aria-describedby="sort"
            placeholder={translatedFields.tip.sortPlaceholder}
          />
        </div>

        <div>
          <label className="form-label">
            {translatedFields.properties.section}
          </label>
          {clientQueryAllSectionQuery.data &&
            clientQueryAllSectionQuery.data.length > 0 && (
              <select
                name="sectionId"
                value={form.sectionId}
                onChange={onChangeForm}
                className="form-select"
                placeholder={translatedFields.tip.sectionPlaceholder}
              >
                <option disabled value="">
                  {translatedFields.tip.sectionPlaceholder}
                </option>
                {clientQueryAllSectionQuery.data.map((item) => {
                  return (
                    <option key={item.id} value={item.id}>
                      {item.name}
                    </option>
                  );
                })}
              </select>
            )}

          {clientQueryAllSectionQuery.data &&
            clientQueryAllSectionQuery.data.length === 0 && <Nodata />}

          {clientQueryAllSectionQuery.isError && (
            <Alert message={clientQueryAllSectionQuery.error} type="error" />
          )}

          {clientQueryAllSectionQuery.isLoading && <AlertLoad />}
        </div>

        <button
          type="submit"
          disabled={updatePostTemplateMutation.isLoading || isDisabledSave}
          className="btn btn-success col col-lg-2 my-4"
        >
          {updatePostTemplateMutation.isLoading && <Spinner classs="me-2" />}
          {translatedFields.operate.update}
        </button>
      </form>
    </Box>
  );
}
